import React, { useState, useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import styled from 'styled-components';
import { motion } from 'framer-motion';
import html2canvas from 'html2canvas';

const InterpretationContainer = styled.div`
  min-height: 100vh;
  background: linear-gradient(135deg, #1a0a2e 0%, #0d0630 100%);
  color: white;
  padding: 20px;
`;

const Header = styled.h1`
  font-size: 2rem;
  margin-bottom: 20px;
  text-align: center;
  background: linear-gradient(to right, #9d4edd, #5a189a);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
`;

const ReportHeader = styled.div`
  max-width: 800px;
  margin: 0 auto 30px;
  text-align: center;
  padding: 20px;
  background: rgba(90, 24, 154, 0.2);
  border-radius: 15px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(157, 78, 221, 0.3);
`;

const QuestionDisplay = styled.h2`
  font-size: 1.3rem;
  color: #e0aaff;
  margin-bottom: 10px;
`;

const DateTimeDisplay = styled.p`
  font-size: 1rem;
  color: #c77dff;
`;

const CardsSection = styled.div`
  max-width: 1200px;
  margin: 0 auto 40px;
`;

const SectionTitle = styled.h2`
  font-size: 1.5rem;
  margin-bottom: 20px;
  color: #e0aaff;
  text-align: center;
`;

const CardsGrid = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
`;

const CardItem = styled.div`
  background: rgba(90, 24, 154, 0.2);
  border-radius: 15px;
  padding: 20px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(157, 78, 221, 0.3);
`;

const CardHeader = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
`;

const CardName = styled.h3`
  font-size: 1.2rem;
  color: #e0aaff;
  margin: 0;
`;

const Position = styled.span`
  background: rgba(224, 170, 255, 0.2);
  padding: 5px 10px;
  border-radius: 20px;
  font-size: 0.9rem;
`;

const CardOrientation = styled.p`
  font-size: 1rem;
  color: ${(props) => props.reversed ? '#ff6b6b' : '#4ecdc4'};
  margin-bottom: 15px;
`;

const CardInterpretation = styled.p`
  font-size: 1rem;
  color: #c77dff;
  line-height: 1.6;
`;

const OverallSection = styled.div`
  max-width: 800px;
  margin: 0 auto 40px;
  background: rgba(90, 24, 154, 0.2);
  border-radius: 15px;
  padding: 30px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(157, 78, 221, 0.3);
`;

const OverallTitle = styled.h2`
  font-size: 1.5rem;
  margin-bottom: 20px;
  color: #e0aaff;
  text-align: center;
`;

const OverallText = styled.p`
  font-size: 1.1rem;
  color: #c77dff;
  line-height: 1.6;
`;

const ActionButtonsContainer = styled.div`
  display: flex;
  justify-content: center;
  gap: 20px;
  flex-wrap: wrap;
  margin-top: 30px;
`;

const ActionButton = styled(motion.button)`
  padding: 15px 30px;
  font-size: 1.1rem;
  border: none;
  border-radius: 50px;
  background: linear-gradient(45deg, #9d4edd, #5a189a);
  color: white;
  cursor: pointer;
  box-shadow: 0 4px 15px rgba(90, 24, 154, 0.3);
  
  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 6px 20px rgba(90, 24, 154, 0.5);
  }
`;

const ShareButton = styled(ActionButton)`
  background: linear-gradient(45deg, #ff9e00, #ff5400);
`;

const ConnectButton = styled(ActionButton)`
  background: linear-gradient(45deg, #00c9ff, #92fe9d);
`;

const TarotInterpretation = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const { question, category, spread, cards } = location.state || { question: '', category: '', spread: null, cards: [] };
  
  const [interpretation, setInterpretation] = useState('');
  const [overallReading, setOverallReading] = useState('');

  // 生成模拟解读内容
  useEffect(() => {
    if (cards.length > 0) {
      // 生成每张牌的解读
      const cardInterpretations = cards.map(card => {
        return {
          card: card.name,
          position: card.position,
          interpretation: `${card.name}在"${card.position}"位置上，${card.isReversed ? '逆位表示...' : '正位表示...'}。这可能意味着在您提出的问题中，这个方面需要特别关注。`,
          isReversed: card.isReversed
        };
      });
      
      setInterpretation(cardInterpretations);
      
      // 生成整体解读
      setOverallReading(`整体来看，这个牌阵${spread.name}揭示了关于您问题"${question}"的深层含义。牌面显示，当前情况受到多个因素的影响，包括过去的经历、现在的选择以及未来的可能性。建议您保持开放的心态，仔细考虑每张牌的指引，并相信自己的直觉。`);
    }
  }, [cards, question, spread]);

  // 分享功能
  const handleShare = async () => {
    const reportElement = document.getElementById('tarot-report');
    if (reportElement) {
      try {
        const canvas = await html2canvas(reportElement);
        const image = canvas.toDataURL('image/png');
        
        // 创建下载链接
        const link = document.createElement('a');
        link.href = image;
        link.download = '塔罗牌解读报告.png';
        link.click();
      } catch (error) {
        console.error('分享失败:', error);
        alert('生成分享图片失败，请重试');
      }
    }
  };

  // 收藏记录
  const handleSaveReading = () => {
    // 这里应该调用API保存记录
    alert('解读已收藏到您的记录中');
  };

  // 再算一次
  const handleRerun = () => {
    navigate('/tarot/question');
  };

  // 连接真人塔罗师
  const handleConnectExpert = () => {
    // 这里应该导航到专家咨询页面
    alert('连接真人塔罗师功能即将上线');
  };

  return (
    <InterpretationContainer>
      <Header>塔罗牌解读报告</Header>
      
      <ReportHeader>
        <QuestionDisplay>问题：{question}</QuestionDisplay>
        <DateTimeDisplay>测算时间：{new Date().toLocaleString()}</DateTimeDisplay>
      </ReportHeader>
      
      <div id="tarot-report">
        <CardsSection>
          <SectionTitle>牌阵解读</SectionTitle>
          <CardsGrid>
            {interpretation && interpretation.map((item, index) => (
              <CardItem key={index}>
                <CardHeader>
                  <CardName>{item.card}</CardName>
                  <Position>{item.position}</Position>
                </CardHeader>
                <CardOrientation reversed={item.isReversed}>
                  {item.isReversed ? '逆位' : '正位'}
                </CardOrientation>
                <CardInterpretation>
                  {item.interpretation}
                </CardInterpretation>
              </CardItem>
            ))}
          </CardsGrid>
        </CardsSection>
        
        <OverallSection>
          <OverallTitle>整体分析</OverallTitle>
          <OverallText>
            {overallReading}
          </OverallText>
        </OverallSection>
      </div>
      
      <ActionButtonsContainer>
        <ActionButton
          whileHover={{ scale: 1.05 }}
          whileTap={{ scale: 0.95 }}
          onClick={handleSaveReading}
        >
          收藏记录
        </ActionButton>
        
        <ShareButton
          whileHover={{ scale: 1.05 }}
          whileTap={{ scale: 0.95 }}
          onClick={handleShare}
        >
          分享报告
        </ShareButton>
        
        <ActionButton
          whileHover={{ scale: 1.05 }}
          whileTap={{ scale: 0.95 }}
          onClick={handleRerun}
        >
          再算一次
        </ActionButton>
        
        <ConnectButton
          whileHover={{ scale: 1.05 }}
          whileTap={{ scale: 0.95 }}
          onClick={handleConnectExpert}
        >
          连接真人塔罗师
        </ConnectButton>
      </ActionButtonsContainer>
    </InterpretationContainer>
  );
};

export default TarotInterpretation;